<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import { vLoading } from 'element-plus';
import { VideoPlayer } from '@videojs-player/vue';
import 'video.js/dist/video-js.css';
import { obsDownload } from '#/utils/obs';
import { useVodPlayer } from '#/hooks/useVodPlayer';
import WatermarkWrapper from '#/components/WatermarkWrapper.vue';

defineOptions({ name: 'VideoViewer' });

const props = defineProps<{
  path: string;
  vodAssetId?: string; // VOD媒资ID
}>();

const domRef = ref<HTMLElement>();

// 使用VOD播放器钩子
const {
  loading: vodLoading,
  error: vodError,
  playInfo,
  getPlayInfo,
  getBestPlayUrl,
  getPlayUrlByQuality
} = useVodPlayer();

const videoLoading = ref(false);
const videoSrc = ref<string>('');
const availableQualities = ref<string[]>([]);
const selectedQuality = ref<string>('');

// 判断是否为VOD资源
const isVodResource = computed(() => {
  return props.path?.startsWith('vod://') || !!props.vodAssetId;
});

// 获取VOD媒资ID
const getVodAssetId = computed(() => {
  if (props.vodAssetId) {
    return props.vodAssetId;
  }
  if (props.path?.startsWith('vod://')) {
    return props.path.replace('vod://', '');
  }
  return null;
});

// 动态播放器配置
const playerOptions = ref({
  autoplay: false,
  controls: true,
  responsive: true,
  fluid: true,
  // 支持HLS流式播放
  html5: {
    vhs: {
      overrideNative: true
    },
    nativeVideoTracks: false,
    nativeAudioTracks: false,
    nativeTextTracks: false
  },
  sources: [{
    src: '',
    type: 'application/x-mpegURL' // 默认HLS格式
  }],
  controlBar: {
    children: [
      'playToggle',
      'volumePanel',
      'currentTimeDisplay',
      'timeDivider',
      'durationDisplay',
      'progressControl',
      'liveDisplay',
      'remainingTimeDisplay',
      'customControlSpacer',
      'playbackRateMenuButton',
      'qualitySelector',
      'pictureInPictureToggle',
      'fullscreenToggle'
    ]
  }
});

// 加载VOD视频
const loadVodVideo = async () => {
  const assetId = getVodAssetId.value;
  if (!assetId) {
    console.error('VOD媒资ID不存在');
    return;
  }

  try {
    videoLoading.value = true;
    console.log('开始获取VOD播放信息:', assetId);
    
    const info = await getPlayInfo(assetId);
    console.log('VOD播放信息:', info);
    
    if (info && info.playUrls.length > 0) {
      // 提取可用清晰度
      availableQualities.value = info.playUrls.map(url => url.quality);
      
      // 获取最佳播放URL
      const bestUrl = getBestPlayUrl(info);
      videoSrc.value = bestUrl;
      
      // 更新播放器配置
      if (playerOptions.value.sources[0]) {
        playerOptions.value.sources[0].src = bestUrl;
        // 根据URL格式设置正确的type
        if (bestUrl.includes('.m3u8')) {
          playerOptions.value.sources[0].type = 'application/x-mpegURL'; // HLS
        } else if (bestUrl.includes('.mpd')) {
          playerOptions.value.sources[0].type = 'application/dash+xml'; // DASH
        } else {
          playerOptions.value.sources[0].type = 'video/mp4'; // MP4
        }
      }
      
      console.log('VOD视频加载完成:', bestUrl);
    } else {
      console.error('VOD播放信息为空');
    }
  } catch (error) {
    console.error('加载VOD视频失败:', error);
  } finally {
    videoLoading.value = false;
  }
};

// 加载OBS视频
const loadObsVideo = () => {
  videoLoading.value = true;
  obsDownload(
    {
      Key: props.path,
    },
    (err: any, result: any) => {
      if (err) {
        console.error('获取OBS视频失败:', err);
        videoLoading.value = false;
        return;
      }

      // 创建视频URL
      if (result.InterfaceResult?.Content) {
        const content = result.InterfaceResult.Content as ArrayBuffer;
        const blob = new Blob([content], {
          type: 'video/mp4'
        });
        videoSrc.value = window.URL.createObjectURL(blob);

        // 更新播放器选项
        if (playerOptions.value.sources[0]) {
          playerOptions.value.sources[0].src = videoSrc.value;
          playerOptions.value.sources[0].type = 'video/mp4';
        }
      }
      videoLoading.value = false;
    },
  );
};

// 统一视频加载入口
const loadVideo = () => {
  if (isVodResource.value) {
    loadVodVideo();
  } else {
    loadObsVideo();
  }
};

// 切换清晰度
const switchQuality = (quality: string) => {
  if (!playInfo.value) return;
  
  const newUrl = getPlayUrlByQuality(quality, playInfo.value);
  if (newUrl && newUrl !== videoSrc.value) {
    videoSrc.value = newUrl;
    selectedQuality.value = quality;
    
    // 更新播放器源
    if (playerOptions.value.sources[0]) {
      playerOptions.value.sources[0].src = newUrl;
    }
    
    console.log('切换清晰度:', quality, newUrl);
  }
};

// 播放器事件处理
const onPlayerMounted = ({ player }: any) => {
  console.log('视频播放器已挂载', player);
  
  // 监听播放器错误
  player.on('error', (error: any) => {
    console.error('播放器错误:', error);
  });
  
  // 监听播放器准备就绪
  player.on('ready', () => {
    console.log('播放器准备就绪');
  });
};

const onPlayerUnmounted = () => {
  console.log('视频播放器已卸载');
};

// 监听路径变化，重新加载视频
watch(() => props.path, (newPath) => {
  if (newPath) {
    // 清理旧的视频URL
    if (videoSrc.value && !isVodResource.value) {
      window.URL.revokeObjectURL(videoSrc.value);
    }
    videoSrc.value = '';
    availableQualities.value = [];
    selectedQuality.value = '';
    
    // 加载新视频
    loadVideo();
  }
}, { immediate: false });

watch(() => props.vodAssetId, (newAssetId) => {
  if (newAssetId) {
    loadVideo();
  }
}, { immediate: false });

onMounted(() => {
  if (props.path || props.vodAssetId) {
    loadVideo();
  }
});

onUnmounted(() => {
  // 只清理OBS创建的Blob URL
  if (videoSrc.value && !isVodResource.value) {
    window.URL.revokeObjectURL(videoSrc.value);
  }
});
</script>

<template>
  <div ref="domRef" class="flex h-[100%] w-full flex-col items-center" v-loading="videoLoading || vodLoading">
    <!-- VOD错误信息 -->
    <div v-if="vodError" class="w-full p-4 bg-red-50 border border-red-200 rounded-md mb-4">
      <p class="text-red-600 text-sm">{{ vodError }}</p>
    </div>
    
    <!-- 清晰度选择器 -->
    <div v-if="isVodResource && availableQualities.length > 1" class="w-full p-3 bg-gray-50 border-b">
      <div class="flex items-center gap-2">
        <span class="text-sm font-medium text-gray-700">清晰度:</span>
        <div class="flex gap-2">
          <button
            v-for="quality in availableQualities"
            :key="quality"
            @click="switchQuality(quality)"
            :class="[
              'px-3 py-1 text-xs rounded-md border transition-colors',
              selectedQuality === quality || (!selectedQuality && quality === availableQualities[0])
                ? 'bg-blue-500 text-white border-blue-500'
                : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
            ]"
          >
            {{ quality }}
          </button>
        </div>
      </div>
    </div>
    
    <div class="w-full h-full flex flex-col items-center justify-center">
      <!-- 带水印的视频播放器 -->
      <div class="w-full h-full flex items-center justify-center">
        <WatermarkWrapper>
          <VideoPlayer 
            v-if="videoSrc" 
            :options="playerOptions" 
            @mounted="onPlayerMounted"
            @unmounted="onPlayerUnmounted" 
          />
        </WatermarkWrapper>
      </div>
      
      <!-- 加载提示 -->
      <div v-if="!videoSrc && !videoLoading && !vodLoading" class="text-gray-500 text-center">
        <p>暂无视频内容</p>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.icon {
  cursor: pointer;
}

:deep(.vjs-control-bar) {
  background-color: rgba(0, 0, 0, 0.7);
}

:deep(.vjs-big-play-button) {
  position: absolute !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
}
</style>
